<template>
  <view class="map-container">
    <!-- 地图组件 -->

    <map
      id="map"
      style="width: 100%; height: 80vh"
      :latitude="center.latitude"
      :longitude="center.longitude"
      :polygons="polygons"
      @regionchange="handleMapDrag"
      @tap="handleMapTap"
      :show-location="true"
      :enable-scroll="true"
      :enable-zoom="true"
      :enable-3D="true"
    >
      <!-- 使用 cover-view 在地图上覆盖UI元素 -->

      <!-- 中心标记 -->
      <cover-view class="center-marker"></cover-view>

      <!-- 提示信息 -->
      <cover-view
        class="info-box"
        :class="{ 'out-of-range': !isInServiceArea }"
      >
        <cover-view v-if="isInServiceArea">当前位置在服务区域内</cover-view>
        <cover-view v-else class="error">当前选择位置超出服务区域</cover-view>

        <cover-view class="coords">
          纬度: {{ currentPos.latitude.toFixed(6) }} 经度:
          {{ currentPos.longitude.toFixed(6) }}
        </cover-view>

        <cover-view
          v-if="!isInServiceArea"
          class="recenter-btn"
          @tap="centerToServiceArea"
        >
          查看最近的服务区域
        </cover-view>

        <!-- 确定按钮 -->
        <cover-view v-else class="confirm-btn" @tap="confirmLocation">
          确定上车位置
        </cover-view>
      </cover-view>
    </map>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";

// 服务区域边界
const serviceAreaPolygon = [
  { latitude: 34.808, longitude: 113.55 }, // 西北角：惠济区附近
  { latitude: 34.805, longitude: 113.58 }, // 北侧：金水区北
  { latitude: 34.79, longitude: 113.61 }, // 东北：郑东新区CBD
  { latitude: 34.765, longitude: 113.625 }, // 东侧：东四环附近
  { latitude: 34.735, longitude: 113.62 }, // 东南：经开区
  { latitude: 34.71, longitude: 113.6 }, // 南侧：南三环
  { latitude: 34.7, longitude: 113.57 }, // 西南：二七区
  { latitude: 34.715, longitude: 113.54 }, // 西侧：中原区
  { latitude: 34.75, longitude: 113.53 }, // 西北：高新区
  { latitude: 34.808, longitude: 113.55 }, // 闭合多边形
];

// 中心点位置
const center = ref({
  latitude: 34.747,
  longitude: 113.625,
});

const currentPos = ref({ ...center.value });
const isInServiceArea = ref(true);

const mapContext = ref(null);

// 地图多边形配置
const polygons = ref([
  {
    points: serviceAreaPolygon,
    strokeWidth: 2,
    strokeColor: "#1E90FF",
    fillColor: "#1E90FF22",
  },
]);

// 初始化地图上下文 (Vue 3 正确写法)
onMounted(() => {
  mapContext.value = uni.createMapContext("map");
  // 设置地图中心为多边形质心
  center.value = getPolygonCenter(serviceAreaPolygon);
  currentPos.value = { ...center.value };
  isInServiceArea.value = isPointInPolygon(
    currentPos.value,
    serviceAreaPolygon
  );
});

// 地图拖拽事件
const handleMapDrag = (e) => {

  if (e.type === "end") {
    mapContext.value.getCenterLocation({
      success: (res) => {
        currentPos.value = {
          latitude: res.latitude,
          longitude: res.longitude,
        };
        isInServiceArea.value = isPointInPolygon(
          currentPos.value,
          serviceAreaPolygon
        );
      },
    });
  }
};

// 点击"最近服务区域"按钮
const centerToServiceArea = () => {
  center.value = getPolygonCenter(serviceAreaPolygon);
  currentPos.value = { ...center.value };
  isInServiceArea.value = true;
  //手机上才能移动，微信开发者工具暂时不支持
  // 强制地图移动到新位置
  mapContext.value.moveToLocation({
    latitude: currentPos.value.latitude,
    longitude: currentPos.value.longitude,
    success: () => {
      console.log("地图移动成功");
    },
    fail: (err) => {
      console.error("地图移动失败:", err);
    },
  });
};

// 确认位置
const confirmLocation = () => {
  uni.showToast({
    title: `位置已确认: ${currentPos.value.latitude}, ${currentPos.value.longitude}`,
    icon: "success",
  });
};

/**
 * 计算多边形中心点（简单平均值法）
 * @param {Array} polygon 多边形顶点数组
 * @returns {Object} {latitude, longitude}
 */
function getPolygonCenter(polygon) {
  let latSum = 0,
    lngSum = 0;
  const len = polygon.length;

  for (const { latitude, longitude } of polygon) {
    latSum += latitude;
    lngSum += longitude;
  }

  return {
    latitude: latSum / len,
    longitude: lngSum / len,
  };
}

/**
 * 判断点是否在多边形内（射线法）
 * @param {Object} point 待测点 {latitude, longitude}
 * @param {Array} polygon 多边形顶点数组 [{latitude, longitude}, ...]
 * @returns {boolean}
 */
function isPointInPolygon(point, polygon) {
  const { latitude, longitude } = point;
  let inside = false;

  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
    const { latitude: lat1, longitude: lng1 } = polygon[i];
    const { latitude: lat2, longitude: lng2 } = polygon[j];

    // 射线与边交点的纬度计算
    const intersect =
      lng1 > longitude !== lng2 > longitude &&
      latitude < ((lat2 - lat1) * (longitude - lng1)) / (lng2 - lng1) + lat1;

    if (intersect) inside = !inside;
  }

  return inside;
}
</script>

<style scoped lang="scss">
.map-container {
  position: relative;
  width: 100%;
  height: 100vh;
}

.center-marker {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 20px;
  height: 20px;
  background-color: #5ca7fc;
  border-radius: 50%;
  border: 2px solid white;
  z-index: 999;
  pointer-events: none; /* 关键修正 */
}

.info-box {
  position: absolute;
  top: 30%;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(255, 255, 255, 0.9);
  padding: 10px 15px;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  max-width: 80%;
  .out-of-range {
    background-color: rgba(255, 240, 240, 0.9);
  }
}

.coords {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
  display: block;
}

.error {
  color: #ff0000;
  font-weight: bold;
}

.recenter-btn {
  margin-top: 10px;
  padding: 8px 12px;
  /* background-color: #1E90FF; */
  background: rgb(56, 56, 56);
  color: white;
  border-radius: 4px;
  font-size: 14px;
  pointer-events: auto;
}

.confirm-btn {
  margin-top: 10px;
  padding: 8px 12px;
  /* background-color: #1E90FF; */
  background: rgb(52, 132, 236);
  color: white;
  border-radius: 4px;
  font-size: 14px;
  pointer-events: auto;
  text-align: center;
}
</style>
